#!/usr/bin/python

'''MisacaShell

Author: Cauly Kan

Date: 2001.10.19

wiki: /wiki/MisacaConverterDesign.wiki

contact: cauliflower.kan@gmail.com

'''

import argparse
import json
import os

from MisacaDetect import VideoSourceDetect
from MisacaDownload import MisacaDownload
from MisacaConvert import MisacaContact, MisacaConvert, _unix as unix

parser = argparse.ArgumentParser(description = "", epilog = "Detect, Download and Convert Bilibili videos.")

parser.add_argument("id", help = "Video identifier which MisacaDetect will automatically find the video source.\n For example: 'av123', 'vid=123', 'ykid=123'")

parser.add_argument("-p, --part", dest = "part", default = "1", type = int, help = "bilibili video part, e.g. 1")

parser.add_argument("-o, --output", dest = "output", help = "The output file location")

parser.add_argument("-f, --format", dest = "format", help = "The output file format, e.g. mp3, avi")

parser.add_argument("--skip-download", action='store_true', dest = "skip", help = "skip the download for those already downloaded.")

try:

    args = parser.parse_args()
    
except:

    print "{:>20}".format("MisacaShell") + ": MisacaShell did nothing and quit."

else: 
    
    config = json.loads(open("os/unix/config.json" if unix() else "os/nonunix/config.json", "r").read(), "utf-8")

    pydir = os.getcwd()
    
    os.chdir(config["dir"].encode("utf-8"))
    
    config["ffmpeg"] ="\"" + config["ffmpeg"].encode("utf-8").replace("$main", pydir) + "\""
    config["cookie"] = config["cookie"].encode("utf-8")

    info = VideoSourceDetect(args.id, args.part, config["cookie"])
    
    out = args.output if args.output is not None else info["name"] + "." + info["format"]
    
    if info is not None:
        
        if len(info["urls"]) > 1:
        
            if not args.skip:
                
                files = MisacaDownload(info, out)
            
            else:
                
                files = ["%s.%d" % (out, i) for i in range(len(info["urls"]))]
            
            MisacaContact(files, (out + ".tmp") if args.format is not None else out, config)
            
        else:
        
            MisacaDownload(info, (out + ".tmp") if args.format is not None else out)
    
        if args.format is not None:
            
            MisacaConvert(out + ".tmp", args.format, out, config)
        
        #os.remove(out + ".tmp")
    
        print "{:>20}".format("MisacaShell") + ": All jobs done. Enjoy yourself."
    


